using System;

namespace Tycho.Parser.Peg {
    public class IdentifierProduction : Production {
        public IdentifierProduction () {
            Name = "identifier";
            ErrorInformation = new ProductionErrorInformation ("identifier");
        }

        public static Terminal CreateTerminal () {
            return new Terminal (new IdentifierProduction ());
        }

        protected override ParseResult ReallyParse (char[] source, int startIndex, ParseContext context, string sourceString, ParseEnvironment parseEnvironment) {
            int index = startIndex;
            char c = source[index];
            if (!(char.IsLetter (c) || c == '_')) {
                return null;
            }

            do {
                index++;
                if (index >= source.Length)
                    break;
                c = source[index];
            } while (char.IsLetterOrDigit (c) || c == '_' || c == '-');

            var identifierTerm = new IdentifierTerm (new string (source, startIndex, index - startIndex), parseEnvironment.SourceFileInformation.CreateSourceInformation (startIndex, index - startIndex));
            return new ParseResult (index, identifierTerm, context);
        }
    }
}